package com.aistudy.file.service.impl;

import com.aistudy.file.config.MinioConfig;
import com.aistudy.file.service.IMinioService;
import com.aistudy.file.utils.FileUploadUtils;
import com.alibaba.nacos.common.utils.IoUtils;
import io.minio.*;
import io.minio.errors.ErrorResponseException;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * Minio 文件操作服务实现
 *
 * @author aistudy
 */
@Service
public class MinioServiceImpl implements IMinioService {
    
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient minioClient;

    /**
     * 上传文件
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        InputStream inputStream = null;
        try {
            String fileName = FileUploadUtils.extractFilename(file);
            inputStream = file.getInputStream();
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(fileName)
                    .stream(inputStream, file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            minioClient.putObject(args);
            return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException("Minio上传文件失败", e);
        } finally {
            IoUtils.closeQuietly(inputStream);
        }
    }

    /**
     * 获取文件访问的签名URL
     */
    @Override
    public String getPresignedObjectUrl(String objectName, Integer expires) throws Exception {
        try {
            // 检查文件是否存在
            if (!checkObjectExist(objectName)) {
                throw new RuntimeException("文件不存在");
            }
            
            // 获取带签名的临时URL
            GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(objectName)
                    .method(Method.GET)
                    .expiry(expires, TimeUnit.SECONDS)
                    .build();
            return minioClient.getPresignedObjectUrl(args);
        } catch (Exception e) {
            throw new RuntimeException("获取文件访问URL失败", e);
        }
    }

    /**
     * 删除文件
     */
    @Override
    public void removeObject(String objectName) throws Exception {
        try {
            RemoveObjectArgs args = RemoveObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(objectName)
                    .build();
            minioClient.removeObject(args);
        } catch (Exception e) {
            throw new RuntimeException("删除文件失败", e);
        }
    }

    /**
     * 检查文件是否存在
     */
    @Override
    public boolean checkObjectExist(String objectName) {
        try {
            StatObjectArgs args = StatObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(objectName)
                    .build();
            minioClient.statObject(args);
            return true;
        } catch (ErrorResponseException e) {
            e.printStackTrace();
            if (e.response().code() == 404) {
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException("检查文件存在状态失败: " + objectName, e);
        }
        return false;
    }

} 